<?php
class Custom_Controller_Action_Admin_Filemanager extends  Custom_Controller_Action_Admin_Controller {
    
	public function indexAction() {
		$this->view->assign('entry_folder','New Folder:');
		$this->view->assign('entry_move','Move:');
		$this->view->assign('entry_copy','Name:');
		$this->view->assign('entry_rename','Name:');
		
		$this->view->assign('button_folder','New Folder');
		$this->view->assign('button_delete','Delete');
		$this->view->assign('button_move','Move');
		$this->view->assign('button_copy','Copy');
		$this->view->assign('button_rename','Rename');
		$this->view->assign('button_upload','Upload');
		$this->view->assign('button_refresh','Refresh'); 
		
		$this->view->assign('error_select','Warning: Please select a directory or file!');
		$this->view->assign('error_directory','Warning: Please select a directory!');
		
		$this->view->assign('directory',BASE_PATH.'/public/uploads/data/');
//		$field = $this->_getParam ( 'field', '' );
//		if (isset($field)) {
//			$this->view->assign('field',$field);
//		} else {
//			$this->view->assign('field','');
//		}
		$field = $this->_getParam ( 'field', 'uploadimage' );
        $this->view->field = $field;
        
        $thumb = $this->_getParam ( 'thumb', 'thumbimage' );
        $this->view->thumb = $thumb;
        
        $preview = $this->_getParam ( 'preview', 'uploadedimage' );
        $this->view->preview = $preview;
//		if (isset($this->request->get['CKEditorFuncNum'])) {
//			$this->view->assign('fckeditor','');// $this->request->get['CKEditorFuncNum'];
//		} else {
//			$this->view->assign('fckeditor','');// false;
//		}
		
	}	
	
	public function imageAction() {
		$model = new Custom_Model_Filemanager();
		$image = $this->getRequest ()->getPost ('image');
		if (isset($image)) {
			$model->resize($image, 170, 100);
		}
	}
	
	public function directoryAction() {	
		$this->_helper->layout->disableLayout ();
        $this->_helper->viewRenderer->setNoRender ();
		$json = array();
		$directoryFrm = $this->getRequest ()->getPost ('directory');
		if (isset($directoryFrm)) {
			$directories = glob(rtrim(UPLOAD_PATH.'/data/' . str_replace('../', '', $directoryFrm), '/') . '/*', GLOB_ONLYDIR);
			if ($directories) {
				$i = 0;
			
				foreach ($directories as $directory) {
					$json[$i]['data'] = basename($directory);
					$json[$i]['attributes']['directory'] = substr($directory, strlen(UPLOAD_PATH.'/data/'));
					
					$children = glob(rtrim($directory, '/') . '/*', GLOB_ONLYDIR);
					
					if ($children)  {
						$json[$i]['children'] = ' ';
					}
					
					$i++;
				}
			}		
		}

		$jsonO = Zend_Json::encode ( $json );
        echo $jsonO;		
	}
	
	public function filesAction() {
		$this->_helper->layout->disableLayout ();
        $this->_helper->viewRenderer->setNoRender ();
        
		$json = array();
		$model = new Custom_Model_Filemanager();
		
		$direct = $this->getRequest()->getPost('directory');
		$w = $this->getRequest()->getPost('width');
		$h = $this->getRequest()->getPost('height');
		
		if($w < 30 || !is_numeric($w)) $w = 170;
		if($h < 30 || !is_numeric($h)) $h = 100;
		
		if($w > 200) $w = 170;
        if($h < 200) $h = 100;
		
		if (isset($direct) && $direct) {
			$directory = UPLOAD_PATH .'/' . 'data/' . str_replace('../', '', $direct);
		} else {
			$directory = UPLOAD_PATH .'/' . 'data/';
		}
		
		$allowed = array(
			'.jpg',
			'.jpeg',
			'.png',
			'.gif'
		);
		
		$files = glob(rtrim($directory, '/') . '/*');
		
		if ($files) {
			foreach ($files as $file) {
				if (is_file($file)) {
					$ext = strrchr($file, '.');
				} else {
					$ext = '';
				}	
				
				if (in_array(strtolower($ext), $allowed)) {
					$size = filesize($file);
		
					$i = 0;
		
					$suffix = array(
						'B',
						'KB',
						'MB',
						'GB',
						'TB',
						'PB',
						'EB',
						'ZB',
						'YB'
					);
		
					while (($size / 1024) > 1) {
						$size = $size / 1024;
						$i++;
					}
//					$thumb = $model->resize(substr($file, strlen(UPLOAD_PATH)), $w, $h);
//					$basename = basename(dirname($_SERVER["SCRIPT_NAME"]));
//					$thumbs = explode($basename,$thumb);
//					$thumb_file = '';
//					$i = 0;
//					foreach($thumbs as $thum) {
//						if($i > 0 && !empty($thum)) {
//							$thumb_file .= str_replace('//','/',$thum);
//						}
//						$i++;
//					}
					$json[] = array(
						'file'     => substr($file, strlen(UPLOAD_PATH .'/' . 'data/')),
						'filename' => basename($file),
						'size'     => round(substr($size, 0, strpos($size, '.') + 4), 2) . $suffix[$i],
						'thumb'    => $model->resize(substr($file, strlen(UPLOAD_PATH)), $w, $h),
					);
				}
			}
		}
		$jsonO = Zend_Json::encode ( $json );
        echo $jsonO;
	}	
	
	public function createAction() {
	    $this->_helper->layout->disableLayout ();
        $this->_helper->viewRenderer->setNoRender ();
		$arr = array();
		$direct = $this->getRequest ()->getPost ('directory');
		$name = $this->getRequest ()->getPost ('name');
		if (isset($direct)) {
			if (isset($name) || $name) {
				$directory = rtrim(UPLOAD_PATH . '/data/' . str_replace('../', '', $direct), '/');							   
				
				if (!is_dir($directory)) {
					$arr['error'] = 'Warning: Please select a directory!';
				}
				
				if (file_exists($directory . '/' . str_replace('../', '', $name))) {
					$arr['error'] = 'Warning: A file or directory with the same name already exists!';
				}
			} else {
				$arr['error'] = 'Warning: Please enter a new name!';
			}
		} else {
			$arr['error'] = 'Warning: Please select a directory!';
		}
		
		if (!isset($arr['error'])) {	
			mkdir($directory . '/' . str_replace('../', '', $name), 0777);
			
			$arr['success'] = 'Success: Directory created!';
		}	
		$json = Zend_Json::encode ( $arr );
        echo $json;
	}
	
	public function deleteAction() {
		$model = new Custom_Model_Filemanager();
		$this->_helper->layout->disableLayout ();
        $this->_helper->viewRenderer->setNoRender ();
		$json = array();
		$path = $this->getRequest()->getPost('path');
		$temp = $this->getRequest()->getPost('cache');
		$cache = isset($temp)?$temp:$this->getRequest()->getPost('path');
		if (isset($path)) {
			$path = rtrim(UPLOAD_PATH . '/data/' . str_replace('../', '', $path), '/');
			$cache = rtrim(UPLOAD_PATH .'/cache/data/' . str_replace('../', '', $cache), '/');
			
			if (!file_exists($path)) {
				$json['error'] = 'Warning: Please select a directory or file!';
			}
			
			if ($path == rtrim(UPLOAD_PATH . '/data/', '/')) {
				$json['error'] = 'Warning: You can not delete this directory!';
			}
		} else {
			$json['error'] = 'Warning: Please select a directory or file!';
		}
		
		if (!isset($json['error'])) {
			if (is_file($path)) {
				unlink($path);
			} elseif (is_dir($path)) {
				$this->recursiveDelete($path);
			}
		    if (is_file($cache)) {
                unlink($cache);
            } elseif (is_dir($cache)) {
                $this->recursiveDelete($cache);
            }
			$json['success'] = 'Success: Your file or directory has been deleted!';
		}				
		
		$jsonO = Zend_Json::encode ( $json );
        echo $jsonO;
	}

	protected function recursiveDelete($directory) {
		if (is_dir($directory)) {
			$handle = opendir($directory);
		}
		
		if (!$handle) {
			return false;
		}
		
		while (false !== ($file = readdir($handle))) {
			if ($file != '.' && $file != '..') {
				if (!is_dir($directory . '/' . $file)) {
					unlink($directory . '/' . $file);
				} else {
					$this->recursiveDelete($directory . '/' . $file);
				}
			}
		}
		
		closedir($handle);
		
		rmdir($directory);
		
		return true;
	}

	public function moveAction() {
		$this->_helper->layout->disableLayout ();
        $this->_helper->viewRenderer->setNoRender ();
		
		$json = array();
		$fromFrm = $this->getRequest()->getPost('from');
		$toFrm = $this->getRequest()->getPost('to');
		
		if (isset($fromFrm) && isset($toFrm)) {
			$from = rtrim(UPLOAD_PATH . '/data/' . str_replace('../', '', $fromFrm), '/');
			
			if (!file_exists($from)) {
				$json['error'] = 'Warning: File or directory does not exist!';
			}
			
			if ($from == UPLOAD_PATH . '/data') {
				$json['error'] = 'Warning: Can not alter your default directory!';
			}
			
			$to = rtrim(UPLOAD_PATH . '/data/' . str_replace('../', '', $toFrm), '/');

			if (!file_exists($to)) {
				$json['error'] = 'Warning: Move to directory does not exists!';
			}	
			
			if (file_exists($to . '/' . basename($from))) {
				$json['error'] = 'Warning: A file or directory with the same name already exists!';
			}
		} else {
			$json['error'] = 'Warning: Please select a directory!';
		}
		
		if (!isset($json['error'])) {
			rename($from, $to . '/' . basename($from));
			
			$json['success'] = 'Success: Your file or directory has been moved!';
		}
		
		$jsonO = Zend_Json::encode ( $json );
        echo $jsonO;
	}	
	
	public function copyAction() {
		$this->_helper->layout->disableLayout ();
        $this->_helper->viewRenderer->setNoRender ();
        
        $model = new Custom_Model_Filemanager();
        
		$json = array();
		
		$path = $this->getRequest()->getPost('path');
        $name = $this->getRequest()->getPost('name');
        
	    if (isset($path) && isset($name)) {
            if ((strlen(utf8_decode($name)) < 3) || (strlen(utf8_decode($name)) > 255)) {
                $json['error'] = 'Warning: Filename must be a between 3 and 255!';
            }
				
			$old_name = rtrim(UPLOAD_PATH . '/data/' . str_replace('../', '', $path), '/');
			
			if (!file_exists($old_name) || $old_name == UPLOAD_PATH . '/data') {
				$json['error'] = 'Warning: Can not copy this file or directory!';;
			}
			
			if (is_file($old_name)) {
				$ext = strrchr($old_name, '.');
			} else {
				$ext = '';
			}		
			
			$new_name = dirname($old_name) . '/' . str_replace('../', '', $name . $ext);
																			   
			if (file_exists($new_name)) {
				$json['error'] = 'Warning: A file or directory with the same name already exists!';
			}			
		} else {
			$json['error'] = 'Warning: Please select a directory or file!';
		}
		
		if (!isset($json['error'])) {
			if (is_file($old_name)) {
				copy($old_name, $new_name);
			} else {
				$this->recursiveCopy($old_name, $new_name);
			}
			
			$json['success'] = 'Success: Your file or directory has been copied!';
		}
		
		$jsonObj = Zend_Json::encode ( $json );
        echo $jsonObj;
	}

	function recursiveCopy($source, $destination) { 
		$directory = opendir($source); 
		
		@mkdir($destination); 
		
		while (false !== ($file = readdir($directory))) {
			if (($file != '.') && ($file != '..')) { 
				if (is_dir($source . '/' . $file)) { 
					$this->recursiveCopy($source . '/' . $file, $destination . '/' . $file); 
				} else { 
					copy($source . '/' . $file, $destination . '/' . $file); 
				} 
			} 
		} 
		
		closedir($directory); 
	} 

	public function foldersAction() {
		$this->_helper->layout->disableLayout ();
        $this->_helper->viewRenderer->setNoRender ();
		$json = $this->recursiveFolders(UPLOAD_PATH. '/data/');
        echo $json;
	}
	
	protected function recursiveFolders($directory) {
		$output = '';
		
		$output .= '<option value="' . substr($directory, strlen(UPLOAD_PATH. '/data/')) . '">' . substr($directory, strlen(UPLOAD_PATH. '/data/')) . '</option>';
		
		$directories = glob(rtrim(str_replace('../', '', $directory), '/') . '/*', GLOB_ONLYDIR);
		
		foreach ($directories  as $directory) {
			$output .= $this->recursiveFolders($directory);
		}
		
		return $output;
	}
	
	public function renameAction() {
		
		$this->_helper->layout->disableLayout ();
        $this->_helper->viewRenderer->setNoRender ();
        
        $model = new Custom_Model_Filemanager();
        
		$json = array();
		$path = $this->getRequest()->getPost('path');
		$name = $this->getRequest()->getPost('name');
		if (isset($path) && isset($name)) {
			if ((strlen(utf8_decode($name)) < 3) || (strlen(utf8_decode($name)) > 255)) {
				$json['error'] = 'Warning: Filename must be a between 3 and 255!';
			}
				
			$old_name = rtrim(UPLOAD_PATH . '/data/' . str_replace('../', '', $path), '/');
			
			if (!file_exists($old_name) || $old_name == UPLOAD_PATH . '/data') {
				$json['error'] = 'Warning: Can not rename this directory!';
			}
			
			if (is_file($old_name)) {
				$ext = strrchr($old_name, '.');
			} else {
				$ext = '';
			}		
			
			$new_name = dirname($old_name) . '/' . str_replace('../', '', $name . $ext);
																			   
			if (file_exists($new_name)) {
				$json['error'] = 'Warning: A file or directory with the same name already exists!';
			}			
		}
		
		if (!isset($json['error'])) {
			rename($old_name, $new_name);
			
			$json['success'] = 'Success: Your file or directory has been renamed!';
		}
		
		$jsonObj = Zend_Json::encode ( $json );
        echo $jsonObj;
	}
	
	public function uploadAction() {
		$this->_helper->layout->disableLayout ();
        $this->_helper->viewRenderer->setNoRender ();
        
        $model = new Custom_Model_Filemanager();
		
		$json = array();
		
		$direct = $this->getRequest()->getPost('directory');
		$files = $_FILES['image'];
		if (isset($direct)) {
			if (isset($files) && $files['tmp_name']) {
				if ((strlen(utf8_decode($files['name'])) < 3) || (strlen(utf8_decode($files['name'])) > 255)) {
					$json['error'] = 'Warning: Filename must be a between 3 and 255!';
				}
					
				$directory = rtrim(UPLOAD_PATH. '/data/' . str_replace('../', '', $direct), '/');
				
				if (!is_dir($directory)) {
					$json['error'] = 'Warning: Please select a directory!';
				}
				
				if ($files['size'] > 30000000000) {
					$json['error'] = 'Warning: File to big please keep below 300kb and no more than 1000px height or width!';
				}
				
				$allowed = array(
					'image/jpeg',
					'image/pjpeg',
					'image/png',
					'image/x-png',
					'image/gif',
					'application/x-shockwave-flash'
				);
						
				if (!in_array($files['type'], $allowed)) {
					$json['error'] = 'Warning: Incorrect file type!';
				}
				
				$allowed = array(
					'.jpg',
					'.jpeg',
					'.gif',
					'.png',
					'.flv'
				);
						
				if (!in_array(strtolower(strrchr($files['name'], '.')), $allowed)) {
					$json['error'] = 'Warning: Incorrect file type!';
				}

				
				if ($files['error'] != UPLOAD_ERR_OK) {
					$json['error'] = 'error_upload_' . $files['error'];
				}			
			} else {
				$json['error'] = 'Warning: Please select a file!';
			}
		} else {
			$json['error'] = 'Warning: Please select a directory!';
		}
		
		if (!isset($json['error'])) {
			$filename = $directory . '/' . basename($files['name']);
			if (@move_uploaded_file($files['tmp_name'], $filename)) {
				$json['success'] = 'Success: Your file has been uploaded!';
			} else {
				$json['error'] = 'Warning: File could not be uploaded for an unknown reason!';
			}
		}
		
		$jsonObj = Zend_Json::encode ( $json );
        echo $jsonObj;
	}
} 
?>